package rest;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.annotation.EnableScheduling;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;

import rest.Config;

/**
 * Created by liuzesen on 16/1/15.
 */

@EnableScheduling
@SpringBootApplication
public class Application extends SpringBootServletInitializer implements EmbeddedServletContainerCustomizer
{
    public static void main(String[] args) throws IOException
    {
        // 将参数读入config
        Config config = Config.getInstance();
        if (args.length != 0)
        {
            for (int i = 0; i < args.length; i++)
            {
                switch (args[i])
                {
                    case "-p":
                        config.setPort(Integer.valueOf(args[i + 1]));
                        i++;
                        break;
                    case "-t":
                        config.setTimeInterval(Long.valueOf(args[i + 1]));
                        i++;
                        break;
                    case "-s":
                        config.setScriptPath(args[i + 1]);
                        break;
                    case "-h":
                        System.out.println("Usage: java " + Application.class.getName()
                                + " <-s /> <-p 8080> <-t 30>\n" +
                                "-s: script path\n" +
                                "-p: server port\n" +
                                "-t: call interval (seconds)");
                        return;
                }
            }
        }

        // 创建文件存储上次调用时间
        File file = new File(config.getFilePath());
        if (file.exists())
        {
            if (!file.delete())
            {
                throw new IOException("Can not delete " + config.getFilePath());
            }
        }
        if (!file.createNewFile())
        {
            throw new IOException("Can not create file in " + config.getFilePath());
        }

        SpringApplication.run(Application.class, args);
    }

    @Override
    public void customize(ConfigurableEmbeddedServletContainer container)
    {
        Config config = Config.getInstance();
        container.setPort(config.getPort());
    }
}